/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

/**
 * 对应接口文档地址
 * http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
 */
package com.wallellen.wechat.message;

import com.alibaba.fastjson.JSONObject;
import com.wallellen.core.http.HttpUtils;
import com.wallellen.wechat.message.template.TemplateMsgBody;
import com.wallellen.wechat.message.template.TemplateMsgData;
import com.wallellen.wechat.token.TokenProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 模板消息接口
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 * @date 2014年12月24日
 */
public class TemplateMsg {

    private static Logger logger = LoggerFactory.getLogger(TemplateMsg.class);

    //设置所属行业接口地址
    public static final String SET_INDUSTRY_URL = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=";
    //添加模板id接口地址
    public static final String GET_TEMPLATE_ID_URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=";
    //发送模板消息接口地址
    public static final String SEND_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

    private String accessToken;

    public TemplateMsg() {
        this.accessToken = TokenProxy.accessToken();
    }

    /**
     * 设置所属行业
     * 接口说明中没有给出
     */
    public void setIndustry(String... industrys) {
        String url = SET_INDUSTRY_URL + this.accessToken;
        JSONObject json = new JSONObject();
        for (int i = 0; i < industrys.length; i++) {
            json.put("industry_id" + i, industrys[i]);
        }
        String data = json.toJSONString();
        HttpUtils.post(url, data);
    }

    /**
     * 获得模板ID
     *
     * @param templateIdShort template_id_short
     * @return template_id
     */
    public String getTemplateId(String templateIdShort) {
        logger.info("get template id,short template id is:" + templateIdShort);
        //构造请求数据
        String url = GET_TEMPLATE_ID_URL + this.accessToken;
        JSONObject json = new JSONObject();
        json.put("template_id_short", templateIdShort);
        String data = json.toJSONString();
        String result = HttpUtils.post(url, data);
        logger.info("post result:" + result);
        //解析请求数据
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson.getString("errcode").equals("0"))
            return resultJson.getString("template_id");
        logger.error("get template id error:" + resultJson.getString("errmsg"));
        return null;
    }

    /**
     * 发送模板消息
     */
    public String send(TemplateMsgBody postData) {
        logger.info("send template message");
        //构造请求数据
        String url = SEND_MSG_URL + this.accessToken;
        JSONObject json = new JSONObject();
        json.put("touser", postData.getTouser());
        json.put("template_id", postData.getTemplateId());
        json.put("url", postData.getUrl());
        json.put("topcolor", postData.getTopcolor());
        JSONObject jsonData = new JSONObject();
        for (TemplateMsgData data : postData.getData()) {
            JSONObject keynote = new JSONObject();
            keynote.put("value", data.getValue());
            keynote.put("color", data.getColor());
            jsonData.put(data.getName(), keynote);
        }
        json.put("data", jsonData);

        String data = json.toJSONString();
        String result = HttpUtils.post(url, data);
        logger.info("post result:" + result);
        //解析请求数据
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson.getString("errcode").equals("0"))
            return resultJson.getString("msgid");

        logger.error("send template message error:" + resultJson.getString("errmsg"));
        return null;
    }


}
